﻿using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using AuctionClassLibrary;
using System.IO;

namespace Server
{
    class ServerMonitor
    {
        private readonly object _lock;
        public List<NetworkStream> NetworkStreams { get; private set; }
        public List<StreamWriter> StreamWriters { get; private set; }
        public List<string> NameList { get; set; }

        public ServerMonitor()
        {
            _lock = new object();
            NetworkStreams = new List<NetworkStream>();
            StreamWriters = new List<StreamWriter>();
            NameList = new List<string>();
        }

        public void AddNetworkStreamAndStreamWriter(NetworkStream networkStream, StreamWriter streamWriter, string name)
        {
            lock (_lock)
            {
                NetworkStreams.Add(networkStream);
                StreamWriters.Add(streamWriter);
                NameList.Add(name);
            }
        }
        public void RemoveNetworkStreamAndStreamWriter(NetworkStream networkStream, StreamWriter streamWriter, string name)
        {
            lock (_lock)
            {
                NetworkStreams.Remove(networkStream);
                StreamWriters.Remove(streamWriter);
                NameList.Remove(name);
            }
        }
        public void BrocastObject(Auction oAuction, BinaryFormatter bf)
        {
            lock (_lock) { NetworkStreams.ForEach(ns => bf.Serialize(ns, oAuction)); }
        }
        public void BroadcastBid(string ip, string bid)
        {
            lock (_lock)
            {
                StreamWriters.ForEach(sw =>
                    {
                        sw.WriteLine(ip + ";" + bid + ";bid");
                        sw.Flush();
                    });
            }
        }
        public void BroadcastBid(string bid)
        {
            lock (_lock)
            {
                StreamWriters.ForEach(sw =>
                {
                    sw.WriteLine(bid);
                    sw.Flush();
                });
            }
        }
        public void BroadCastMessage(string message)
        {
            lock (_lock)
            {
                try
                {
                    StreamWriters.ForEach(sw =>
                    {
                        sw.WriteLine(message);
                        sw.Flush();
                    });
                }
                catch (IOException) { }
            }
        }
    }
}